<?php
namespace App\Services\Core\Store\Jiujiu;

use App\Helpers\RestResponseFactory;
use App\Helpers\RestUtils;
use App\Models\Factory\ThirdapilogFactory;
use App\Models\Factory\UserLoanQuotaFactory;
use App\Models\Orm\Identity;


/**
 * 99贷对接
 * Class JiujiuService
 * @package App\Services\Core\Store\Jiujiu
 */
class JiujiuService
{

    /**
     * 筛选用户
     * @param $data
     */
    public static function filterUser($userphone)
    {
        $user_identity = Identity::where('userphone',$userphone)->first();

        if(empty($user_identity))
        {
            return RestResponseFactory::ok(RestUtils::getStdObj(),1005,1005,RestUtils::getErrorMessage(1005));

        }
        self::Send($user_identity);

    }



    /**
     * 向合作方发送数据
     * @return mixed
     */
    public static function Send($data)
    {
        $loanMoney = self::getUserLoadMoney($data['userphone']);
        if($loanMoney >= 3)
        {
            $params = array(
                'name'   => $data['name'],
                'mobile' => $data['userphone'],
                'sex'    => $data['sex'],
                'sqje'   => $loanMoney,
                'sqqx'   => 12,
                'city'   => $data['city']
            );
            $dataJson = json_encode($params,JSON_UNESCAPED_UNICODE);
            $en       = openssl_encrypt($dataJson,'des-ecb',JiujiuConfig::$key_des);
            $ff       = base64_encode($en);
            $reqData  = base64_decode($ff);
            $sign     = self::sign($reqData);

            $sendParams = [
                'merchantId' => JiujiuConfig::$merchantId_online,
                'reqData'    => $reqData,
                'sign'       => $sign
            ];


            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, JiujiuConfig::$url_online);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $sendParams);

            $res = curl_exec($ch);
            curl_close($ch);

            $response = json_decode($res,true);
            // 创建推送日志
            $createlogdata = array(
                'uid'          => $data['uid'],
                'userphone'    => $data['userphone'],
                'code'         => '',
                'message'      => $response['msg'],
                'status'       => ($response['result'] == '000000') ? 1 : 2,
                'type'         => 8,
                'created_at'   => date('Y-m-d H:i:s')
            );
            ThirdapilogFactory::createlog($createlogdata);
        }

    }


    /**RSA签名函数
     * $data为待签名数据，比如URL
     * 签名用游戏方的保密私钥，必须是没有经过pkcs8转换的.结果需要用base64编码以备在URL中传输
     * return Sign 签名
     */

    public static function sign($data)
    {
        $priKey = file_get_contents('key/jiujiu/rsa_private_key.pem');
        //转换为openssl密钥，必须是没有经过pkcs8转换的私钥
        $res = openssl_get_privatekey($priKey);
        //调用openssl内置签名方法，生成签名$sign
        openssl_sign($data, $sign, $res);
        openssl_free_key($res);
        $sign = base64_encode($sign);
        return $sign;
    }



    public static function getUserLoadMoney($userphone)
    {
        // 贷款额度（单位：万）
        $LoanAmount = UserLoanQuotaFactory::getUserLoanQuota($userphone);
        $Amount = $LoanAmount != false&&isset($LoanAmount['quota_money']) ? $LoanAmount['quota_money'] : 0;
        return round($Amount/10000);
    }




}
